package com.rpp.utils;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import java.io.IOException;

/**
 * @Description
 * @Author peng
 * @Date 2020/8/11 9:46 上午
 */
public class JsonUtil {
    private static final ObjectMapper mapper = new ObjectMapper();

    static {
        //Null 处理为 空字符
        mapper.configure(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, false);
        //字段为NULL或者""的时候不会列入
        mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
        // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
        mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    }

    /**
     * JSON转Object
     *
     * @param string
     * @param clazz
     * @return
     */
    public static <T> T toObject(String string, Class<T> clazz) {
        T t = null;
        try {
            t = mapper.readValue(string, clazz);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return t;
    }

    /**
     * Object转JSON
     *
     * @param <T>
     * @param obj
     * @return
     */
    public static <T> String toJson(T obj) {
        String value = null;
        try {

            value = mapper.writeValueAsString(obj);
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return value;
    }
}
